#!/usr/bin/env python3
from scapy.all import *
import sys

# 自定义 EtherType，对应你在 P4 parser 中设置的值
SR_ETH_TYPE = 0x0908

# 自定义的源路由头格式，和 P4 中定义保持一致
class SourceRoute(Packet):
    name = "SourceRoute"
    fields_desc = [
        ByteField("path_len", 0),
        ByteField("cur_index", 0),
        FieldListField("port_list", [], ByteField("port", 0), length_from=lambda pkt: pkt.path_len)
    ]

# 绑定该 EtherType 到我们的自定义 SourceRoute 包结构
bind_layers(Ether, SourceRoute, type=SR_ETH_TYPE)

def handle_packet(pkt):
    if SourceRoute in pkt:
        sr = pkt[SourceRoute]
        print(f"\n📦 Captured SourceRoute Packet:")
        print(f"  ➤ path_len  = {sr.path_len}")
        print(f"  ➤ cur_index = {sr.cur_index}")
        print(f"  ➤ port_list = {sr.port_list}")
        print(f"  ➤ Raw payload = {bytes(pkt[SourceRoute].payload).hex()}")
    else:
        print("\n[!] Non-SourceRoute Packet captured")

if __name__ == '__main__':
    iface = "eth0"
    print(f"🌐 Listening on interface {iface} for EtherType 0x{SR_ETH_TYPE:04x} ...")
    sniff(iface=iface, prn=handle_packet, filter=f"ether proto 0x{SR_ETH_TYPE:04x}", store=0)
